package com.dd.cloud.user.service.pres.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dd.cloud.user.entity.pres.DrugsDirectory;
import com.dd.cloud.user.entity.pres.DrugsPoison;
import com.dd.cloud.user.mapper.pres.DrugsPoisonMapper;
import com.dd.cloud.user.req.pres.PresCreateDrugsReq;
import com.dd.cloud.user.service.pres.IDrugsDirectoryService;
import com.dd.cloud.user.service.pres.IDrugsPoisonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 有毒中药材记录表 服务实现类
 * </p>
 *
 * @author czg
 * @since 2022-07-26
 */
@Service
public class DrugsPoisonServiceImpl extends ServiceImpl<DrugsPoisonMapper, DrugsPoison> implements IDrugsPoisonService {
    @Autowired
    private IDrugsDirectoryService drugsDirectoryService;

    /**
     * 通过药品名查询有毒药品
     *
     * @param names
     * @return
     */
    @Override
    public List<DrugsPoison> getDrugsPoison(String names) {
        String[] nameStr = names.split(",");
        QueryWrapper<DrugsPoison> qw = new QueryWrapper<>();
        qw.lambda().in(DrugsPoison::getHerbName, nameStr);
        List<DrugsPoison> list = list(qw);
        return list;
    }

    /**
     * 获取有毒药材下标
     *
     * @param reqs
     * @return
     */
    @Override
    public List<Integer> getDrugsPoisonIndex(List<PresCreateDrugsReq> reqs) {
        Set<Integer> set = new HashSet<>();
        int size = reqs.size();
        for (int i = 0; i < size; i++) {
            PresCreateDrugsReq req = reqs.get(i);
            QueryWrapper<DrugsPoison> qw = new QueryWrapper<>();
            qw.lambda().in(DrugsPoison::getHerbName, req.getHerbName())
                    .last("limit 1");
            DrugsPoison one = getOne(qw);
            if (one != null) {
                set.add(i);
            }
            LambdaQueryWrapper<DrugsDirectory> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DrugsDirectory::getHerbName, req.getHerbName())
                    .last("limit 1");
            DrugsDirectory drugsDirectory = drugsDirectoryService.getOne(queryWrapper);
            if (drugsDirectory != null) {
                BigDecimal dosage = BigDecimal.valueOf(req.getDrugallnum());
                if (dosage.intValue() > drugsDirectory.getMaxDose().intValue()) {
                    set.add(i);
                }
            }
        }
        List<Integer> list = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(set)) {
            list.addAll(set);
        }
        return list;

    }
}
